package zjc.bookkeeping.activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.navigation.NavigationView;
import com.google.gson.Gson;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.speech.SpeechRecognizerAidl;


import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Connection;
import java.util.List;

import zjc.bookkeeping.PhotoRecognition.PhotoRecognitionActivity;
import zjc.bookkeeping.R;
import zjc.bookkeeping.db.AccountBean;
import zjc.bookkeeping.db.DBManager;
import zjc.bookkeeping.db.UserBean;
import zjc.bookkeeping.fragment.HomeFragment;
import zjc.bookkeeping.fragment.StatisticsFragment;
import zjc.bookkeeping.minepage.aAssetaccount.AssetaccountActivity;
import zjc.bookkeeping.minepage.bClassificationkeywords.ClassificationkeywordsMainActivity;
import zjc.bookkeeping.minepage.cClassificationmanagement.ClassificationmanagementMainActivity;
import zjc.bookkeeping.minepage.dAccountbookmanagement.AccountbookmanagementMainActivity;
import zjc.bookkeeping.minepage.dDatamanagement.DatamanagementMainActivity;
import zjc.bookkeeping.minepage.zAcountBinding.AcountBindingActivity;
import zjc.bookkeeping.model.Account;
import zjc.bookkeeping.model.Consumption;
import zjc.bookkeeping.model.User;
import zjc.bookkeeping.server.Itp;
import zjc.bookkeeping.server.Network;
import zjc.bookkeeping.server.Util;
import zjc.bookkeeping.service.AccountService;
import zjc.bookkeeping.service.ConsumptionService;
import zjc.bookkeeping.service.UserService;
import zjc.bookkeeping.service.imp.AccountServiceImp;
import zjc.bookkeeping.service.imp.ConsumptionServiceImp;
import zjc.bookkeeping.service.imp.UserServiceImp;
import zjc.bookkeeping.tools.ToolsClass;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener {
    private HomeFragment homeFragment;
    private StatisticsFragment statisticsFragment;

    private LinearLayout tab_ll_home;
    private LinearLayout tab_ll_statistics;

    private ImageView tab_iv_home;
    private ImageView tab_iv_statistics;

    private TextView tab_tv_home;
    private TextView tab_tv_statistics;

    private zjc.bookkeeping.tools.drawImg di_head;

    private NavigationView nav_view;
    private DrawerLayout drawer_layout;

    private TextView di_user_name;
    private RelativeLayout di_user;

    private String qq_nickname = "未登录";
    private String figureurl_1 = "";// 40*40的qq头像

    private PopupWindow popupWindow;
    private View contentView;
    private View speechView;
    private Button button_speech;
    private TextView sppech_text;
    private boolean onlineFlag = false;
    AccountService accountService = new AccountServiceImp();

    private static final int GET_RECODE_AUDIO = 1;
    private static String[] PERMISSION_AUDIO = {
            Manifest.permission.RECORD_AUDIO
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_main);
        SharedPreferences preferences = getSharedPreferences("userInfo",
                Activity.MODE_PRIVATE);
        SpeechUtility.createUtility(MainActivity.this, SpeechConstant.APPID +"=92bc5f7a");
//        Itp itp = new Itp();
//
//            new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    itp.Itp("支付宝到账100元。");
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();

//        if (preferences.getString("uid","null") != "null"){
//            di_user_name.setText(preferences.getString("nickname","神秘用户"));
//            URL url = null;
//            try {
//                url = new URL(preferences.getString("avatar","null"));
//                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                conn.setDoInput(true);
//                conn.connect();
//                InputStream is = conn.getInputStream();
//                Bitmap bitmap = BitmapFactory.decodeStream(is);
//                di_head.setImageBitmap(bitmap);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
            //String account = preferences.getString("account", "");
        initControls();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Util.go();
//                Connection conn = Util.openConnection();
//                Util.query(conn,"select * from user");
//            }
//        }).start();

//        if (getIntent().getExtras() != null) {
//            Log.i("intent", "intent");
//            Bundle bundle = getIntent().getExtras();
//            int method = bundle.getInt("method");
//            figureurl_1 = bundle.getString("figureurl_1");
//            qq_nickname = bundle.getString("qq_nickname");
//            if (method == 0) {
//                new Thread() {
//                    @Override
//                    public void run() {
//                        // Log.i("qqnickname", qq_nickname);
//                        showUserName(qq_nickname);
//                    }
//                }.start();
//                new Thread() {
//                    @Override
//                    public void run() {
//                        URL url = null;
//                        try {
//                            url = new URL(figureurl_1);
//                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//                            conn.setDoInput(true);
//                            conn.connect();
//                            InputStream is = conn.getInputStream();
//                            Bitmap bitmap = BitmapFactory.decodeStream(is);
//                            showUserAvatar(bitmap);
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }.start();
//            } else {
//                new Thread() {
//                    @Override
//                    public void run() {
//                        showUserName("神秘用户");
//                    }
//                }.start();
//            }
//        }

        initControlsEvent();
        loadFragment(homeFragment);
        showPopwindow(contentView);
    }
//
//    private void showUserName(String name) {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                di_user_name.setText(name);
//            }
//        });
//    }
//
//    private void showUserAvatar(Bitmap bitmap) {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                di_head.setImageBitmap(bitmap);
//            }
//        });
//    }

    @Override
    protected void onStart() {
        super.onStart();
        UserBean userBean = DBManager.findUser();
        if (userBean != null){
            di_user_name.setText(userBean.getUser_name());
            List<AccountBean> accountBeanList = DBManager.getAllAccount();
            for (int i=0; i<accountBeanList.size() ;i++){
                if (accountBeanList.get(i).getAccount_key() == null){
                    Account account = new Account();
                    String uid = null;
                    account.setAccountId("");
                    account.setAccountName(accountBeanList.get(i).getAccount_name());
                    account.setAccountRemarks("");
                    account.setAccountTime(accountBeanList.get(i).getAccount_time());
                    account.setAccountType(accountBeanList.get(i).getAccount_kind());
                    account.setAccountUid("");
                    account.setGrade(3);
                    account.setUserId(userBean.getUser_id());
                    account.setUserRemarks(userBean.getUser_name());
                    uid = accountService.addAccount(account);
                    accountBeanList.get(i).setAccount_key(uid);
                    DBManager.updateAccountbyid(accountBeanList.get(i));
                }
            }
        }else {
            di_user_name.setText("未登录");
        }
    }




    private void loadFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//        用fragment视图控件替换activity_main.xml中的FrameLayout控件
        fragmentTransaction.replace(R.id.fl_main, fragment);
        fragmentTransaction.commit();

        if (fragment instanceof HomeFragment) {
            tab_iv_home.setImageResource(R.drawable.archive_h);
            tab_tv_home.setTextColor(getResources().getColor(R.color.white));
        } else if (fragment instanceof StatisticsFragment) {
            tab_iv_statistics.setImageResource(R.drawable.chartsquare_h);
            tab_tv_statistics.setTextColor(getResources().getColor(R.color.white));
        }
    }

    //    载入控件,实例化
    private void initControls() {

        //初始化识别无UI识别对象
//使用SpeechRecognizer对象，可根据回调消息自定义界面；
        SpeechRecognizer mIat = SpeechRecognizer.createRecognizer(MainActivity.this, mInitListener);

//设置语法ID和 SUBJECT 为空，以免因之前有语法调用而设置了此参数；或直接清空所有参数，具体可参考 DEMO 的示例。
        mIat.setParameter( SpeechConstant.CLOUD_GRAMMAR, null );
        mIat.setParameter( SpeechConstant.SUBJECT, null );
//设置返回结果格式，目前支持json,xml以及plain 三种格式，其中plain为纯听写文本内容
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "plain");
//此处engineType为“cloud”
        mIat.setParameter( SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
//设置语音输入语言，zh_cn为简体中文
        mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
//设置结果返回语言
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
// 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
//取值范围{1000～10000}
        mIat.setParameter(SpeechConstant.VAD_BOS, "4000");
//设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
//自动停止录音，范围{0~10000}
        mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
//设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT,"1");

        tab_ll_home = findViewById(R.id.ll_home);
        tab_iv_home = findViewById(R.id.iv_home);
        tab_tv_home = findViewById(R.id.tv_home);

        speechView = LayoutInflater.from(MainActivity.this).inflate(
                R.layout.speech_pop, null);
        button_speech = speechView.findViewById(R.id.button_speech);
        sppech_text = speechView.findViewById(R.id.sppech_text);
        button_speech.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN){
                    Log.e("按下","chengg");
//开始识别，并设置监听器
                    mIat.startListening(mRecogListener);
                }else if (motionEvent.getAction() == MotionEvent.ACTION_UP){
                    Log.e("放开","chengg");
                    mIat.stopListening();
                }
                return true;
            }
        });
        contentView = LayoutInflater.from(MainActivity.this).inflate(
                R.layout.home_pop, null);

        tab_ll_statistics = findViewById(R.id.ll_statistics);
        tab_iv_statistics = findViewById(R.id.iv_statistics);
        tab_tv_statistics = findViewById(R.id.tv_statistics);

        homeFragment = new HomeFragment();
        statisticsFragment = new StatisticsFragment();

        di_user = findViewById(R.id.di_user);
        //di_user.setOnClickListener(this);
        //头像
        di_head = findViewById(R.id.di_head);
        di_head.setOnClickListener(this);
        //用户名
        di_user_name = findViewById(R.id.di_user_name);
        di_user_name.setOnClickListener(this);
        //左侧隐藏的NavigationView布局
        nav_view = (NavigationView) findViewById(R.id.nav_view);
        nav_view.setNavigationItemSelectedListener(this);//nva菜单的Item点击事件钮监听
        //activity_main文件内最外层布局
        drawer_layout = (DrawerLayout) findViewById(R.id.ac_main);
        drawer_layout.setOnClickListener(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            tab_tv_home.setAutoSizeTextTypeUniformWithConfiguration(1,18,1, TypedValue.COMPLEX_UNIT_SP);
            tab_tv_statistics.setAutoSizeTextTypeUniformWithConfiguration(1,18,1, TypedValue.COMPLEX_UNIT_SP);
        }
    }

    //    点击事件
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_home:
                resetImageAndTextColor();
                loadFragment(homeFragment);
                di_user_name.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_statistics:
                resetImageAndTextColor();
                loadFragment(statisticsFragment);
                di_user_name.setVisibility(View.GONE);
                break;
            case R.id.di_user_name:
                if (di_user_name.getText().equals("未登录")) {
                    Intent intent = new Intent(this, SigninActivity.class);
                    startActivity(intent);
                    Toast.makeText(MainActivity.this, di_user_name.getText(), Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.di_head:
                drawer_layout.openDrawer(GravityCompat.START);//设置左边菜单栏显示出来
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 1:
                boolean audioAccepted = (grantResults[0]==PackageManager.PERMISSION_GRANTED);
                if (audioAccepted){
                    Log.e("录音权限","success");
                    showPopwindow(speechView);
                    popupWindow.showAtLocation(speechView, Gravity.BOTTOM, 0, 0);
                }else {
                    Toast.makeText(this, "请开启录音权限", Toast.LENGTH_SHORT).show();
                    Log.e("权限","fail");
                }
                break;
            case 111:
                boolean cameraAccepted = (grantResults[0]==PackageManager.PERMISSION_GRANTED);
                if(cameraAccepted){
                    //授权成功之后，调用系统相机进行拍照操作等
                    Log.e("权限","success");
                    Intent intent = new Intent(this, PhotoRecognitionActivity.class);
                    startActivity(intent);
                }else{
                    //用户授权拒绝之后，友情提示一下就可以了
                    Toast.makeText(this, "请开启拍照权限", Toast.LENGTH_SHORT).show();
                    Log.e("权限","fail");
                }
                break;
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void gophone(View v) {
        String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        int i = 0;
        boolean flag = false;
        if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(this, PhotoRecognitionActivity.class);
            startActivity(intent);
        }
        for (String permission : permissions) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                //this.requestPermissions(permissions, i++);
                flag = true;
                break;
            }
        }
        if (flag) ActivityCompat.requestPermissions(this,permissions,111);

    }

    //    重置图片和文字颜色
    private void resetImageAndTextColor() {
        tab_iv_home.setImageResource(R.drawable.archive);
        tab_tv_home.setTextColor(getResources().getColor(R.color.shenblue));

        tab_iv_statistics.setImageResource(R.drawable.chartsquare);
        tab_tv_statistics.setTextColor(getResources().getColor(R.color.shenblue));
    }

    private void initControlsEvent() {
        tab_ll_home.setOnClickListener(this);
        tab_ll_statistics.setOnClickListener(this);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav1:
                Toast.makeText(MainActivity.this, "资产账户", Toast.LENGTH_SHORT).show();
                // Intent 去设置要跳转的页面
                Intent intent1 = new Intent(this, AssetaccountActivity.class);
                // 进行跳转
                startActivity(intent1);
                break;
            case R.id.nav2:
                Toast.makeText(MainActivity.this, "分类关键词", Toast.LENGTH_SHORT).show();
                Intent intent2 = new Intent(this, ClassificationkeywordsMainActivity.class);
                startActivity(intent2);
                break;
            case R.id.nav3:
                Toast.makeText(MainActivity.this, "分类管理", Toast.LENGTH_SHORT).show();
                Intent intent3 = new Intent(this, ClassificationmanagementMainActivity.class);
                startActivity(intent3);
                break;
            case R.id.nav4:
                Toast.makeText(MainActivity.this, "账本管理", Toast.LENGTH_SHORT).show();
                Intent intent4 = new Intent(this, AccountbookmanagementMainActivity.class);
                startActivity(intent4);
                break;
            case R.id.nav5:
                Toast.makeText(MainActivity.this, "数据管理", Toast.LENGTH_SHORT).show();
                Intent intent5 = new Intent(this, DatamanagementMainActivity.class);
                startActivity(intent5);
                break;
            case R.id.nav10:
                Toast.makeText(MainActivity.this, "账号安全与绑定", Toast.LENGTH_SHORT).show();
                Intent intent10 = new Intent(this, AcountBindingActivity.class);
                startActivity(intent10);
                break;
            case R.id.nav6:
                Toast.makeText(MainActivity.this, "主题模式暂未开发", Toast.LENGTH_SHORT).show();
//                Intent intent5 = new Intent(this, ThememodeActivity.class);
//                startActivity(intent5);
                break;
            case R.id.nav7:
                Toast.makeText(MainActivity.this, "使用手册暂未开发", Toast.LENGTH_SHORT).show();
//                Intent intent6 = new Intent(this, UserManualActivity.class);
//                startActivity(intent6);
                break;
            case R.id.nav8:
                Toast.makeText(MainActivity.this, "建议与反馈暂未开发", Toast.LENGTH_SHORT).show();
//                Intent intent7 = new Intent(this, SuggestionsfeedbackActivity.class);
//                startActivity(intent7);
                break;
            case R.id.nav9:
                Toast.makeText(MainActivity.this, "关于我们暂未开发", Toast.LENGTH_SHORT).show();
//                Intent intent8 = new Intent(this, AboutusActivity.class);
//                startActivity(intent8);
                break;
        }
        return false;
    }

//    底部菜单
private void showPopwindow(View v) {
    //加载弹出框的布局
    popupWindow = new PopupWindow(v,
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    popupWindow.setFocusable(true);// 取得焦点
    //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
    popupWindow.setBackgroundDrawable(new BitmapDrawable());
    //点击外部消失
    popupWindow.setOutsideTouchable(true);
    //设置可以点击
    popupWindow.setTouchable(true);
    //进入退出的动画，指定刚才定义的style
    popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);

    // 按下android回退物理键 PopipWindow消失解决

}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){
            if(popupWindow!=null&&popupWindow.isShowing()){
                popupWindow.dismiss();
                sppech_text.setText("");
                return true;
            }
        }
        return false;
    }

    /**
     * 按钮的监听
     * @param v
     */
    public void openchoice(View v) {
        //从底部显示
        showPopwindow(contentView);
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    public void speech(View v){
        int permission = ActivityCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.RECORD_AUDIO);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, PERMISSION_AUDIO,
                    GET_RECODE_AUDIO);
        }else {
            showPopwindow(speechView);
            popupWindow.showAtLocation(speechView, Gravity.BOTTOM, 0, 0);
        }


    }



    /**
     * 初始化监听器
     */
    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.e("speech", "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Log.e("初始化失败，错误码：", String.valueOf(code));
            }
        }
    };

    /**
     * 听写监听器
     */
    private RecognizerListener mRecogListener = new RecognizerListener() {
        @Override
        public void onVolumeChanged(int volume, byte[] date) {
            Log.e("当前正在说话，音量大小：" , String.valueOf(volume));
        }

        @Override
        public void onBeginOfSpeech() {

        }

        @Override
        public void onEndOfSpeech() {
            // 此回调表示：检测到了语音的尾端点，已经进入识别过程，不再接受语音输入
            Log.e("结束","结束说话");
        }

        @Override
        public void onResult(RecognizerResult results, boolean b) {

            Log.d("speech_result", results.getResultString());
            sppech_text.setText(results.getResultString());


        }

        @Override
        public void onError(SpeechError speechError) {

        }

        @Override
        public void onEvent(int i, int i1, int i2, Bundle bundle) {

        }
    };



}